package com.example.testcache1.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;

/**
 * 绗笁绾х紦瀛�
 * 
 * sdcard鐨勭紦瀛�
 * 
 * @author bm
 */
public class DiskCache {

	public static final int DEFAULT_WIDTH = 200;
	public static final int DEFAULT_HEIGHT = 200;

	private static final String DEFAULT_CACHE_PATH;

	private File mCacheDirectory;
	private int mWidth = DEFAULT_WIDTH;
	private int mHeight = DEFAULT_HEIGHT;

	static {
		File file = new File(Environment.getExternalStorageDirectory(), "DiskCache");
		DEFAULT_CACHE_PATH = file.getAbsolutePath();
	}

	public DiskCache() {
		this(DEFAULT_CACHE_PATH);
	}

	public DiskCache(String cachePath) {
		mCacheDirectory = new File(cachePath);
		mCacheDirectory.mkdirs();
	}

	/**
	 * 鑾峰彇鍒板綋鍓嶇紦瀛樼殑鐩綍
	 * 
	 * @return
	 */
	public String getCacheFile() {
		return mCacheDirectory.getAbsolutePath();
	}

	public DiskCache setBitmapSize(int widht, int heith) {
		mWidth = widht;
		mHeight = heith;
		return this;
	}

	/**
	 * 灏嗗浘鐗囩紦瀛樺埌鏈湴sdcard
	 * 
	 * @param key
	 */
	public void put(String key, Bitmap bmp) {
		File saveFile = new File(mCacheDirectory, key);
		try {
			FileOutputStream fos = new FileOutputStream(saveFile);
			bmp.compress(CompressFormat.PNG, 100, fos);
			fos.flush();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void save(String key, InputStream is) throws IOException {

		File saveFile = new File(mCacheDirectory, key);

		FileOutputStream fos = new FileOutputStream(saveFile);

		byte[] tmp = new byte[4086];
		int len = 0;

		while ((len = is.read(tmp)) != -1) {
			fos.write(tmp, 0, len);
		}

		fos.flush();
		fos.close();
	}

	/**
	 * 浠庢湰鍦版枃浠朵腑鏍规嵁鎵�粰鐨凨ey璇诲彇鍑哄搷搴旂殑缂撳瓨
	 * 
	 * @param key
	 */
	public Bitmap get(String key) {
		Bitmap bmp = null;

		File file = new File(mCacheDirectory, key);

		if (file.exists()) {
			bmp = BitmapUtils.decodeFile(file.getAbsolutePath(), mWidth, mHeight);
		}

		return bmp;
	}
}